//
//  TypeListViewController.m
//  XDCommonApp
//
//  Created by maboyi on 14-6-24.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "TypeListViewController.h"
#import "TypeListTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "GoodsDetailViewController.h"
@interface TypeListViewController ()

@end

@implementation TypeListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)backPrePage{
    [headerView free];
    [footerView free];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    self.titleLabel.text = _titleName;
    
    dataArray = [[NSMutableArray alloc] init];
    
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT - UI_NAVIGATION_BAR_HEIGHT)];
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.contentView addSubview:myTableView];

    headerView = [MJRefreshHeaderView header];
    headerView.scrollView = myTableView;
    headerView.delegate  = self;

    footerView = [MJRefreshFooterView footer];
    footerView.scrollView = myTableView;
    footerView.delegate  = self;

    faildedIV = [[UIImageView alloc] initWithFrame:CGRectMake((UI_SCREEN_WIDTH-138)/2, (UI_MAINSCREEN_HEIGHT - UI_NAVIGATION_BAR_HEIGHT - 78)/2, 138, 78)];
    faildedIV.image = [UIImage imageNamed:@"refreshFailed"];
    faildedIV.backgroundColor = [UIColor clearColor];
    faildedIV.hidden = YES;
    [self.contentView addSubview:faildedIV];

    [self getDataWithSign:@"0"];
}

- (void)getDataWithSign:(NSString *)type{
    faildedIV.hidden = YES;
    if ([XDTools NetworkReachable])
    {
        NSDictionary * dic = @{@"cat_id": _suppliers_id,
                               @"page": [NSString stringWithFormat:@"%d",currentPage],
                               @"pageSize": @"10"};


        NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dic];
        NSMutableString *params = [[NSMutableString alloc] init];
        for (id keys in muDict) {
            [params appendFormat:@"&%@=%@",keys,[muDict objectForKey:keys]];
        }
//        NSRange rang = [params rangeOfString:@"?"];
//        if(rang.location == NSNotFound){
//            NSRange rangAnd = [params rangeOfString:@"&"];
//            [params replaceCharactersInRange:rangAnd withString:@"?"];
//        }

        NSString *urlStr = [NSString stringWithFormat:@"http://www.xindaoapp.com/maodai/plugins/API.v1.0/?&a=category&m=activitylist%@",params];
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        DDLOG(@"urlStr:%@", urlStr);
        NSURL *url = [NSURL URLWithString:urlStr];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request setTimeOutSeconds:12];



        __weak ASIHTTPRequest * mrequest = request;
        [request setCompletionBlock:^{

            [XDTools hideProgress:self.view];

            NSDictionary *tempDic = [XDTools  JSonFromString:[mrequest responseString]];

            if ([[tempDic objectForKey:@"result"] intValue] == 1)
            {

                if (type.intValue) {
                    [dataArray addObjectsFromArray:tempDic[@"data"]];
                }else{
                    dataArray = [NSMutableArray arrayWithArray:tempDic[@"data"]];
                }

                if (!dataArray.count) {
                    faildedIV.hidden = NO;
                }

                [myTableView reloadData];

                totalCount = dataArray.count;
//                if (totalCount == [tempDic[@"data"][@"count"] intValue]) {
//                    totalCount = -999;
//                }
                [headerView endRefreshing];
                [footerView endRefreshingWithoutIdle];
            }
            else
            {

                [XDTools showTips:[tempDic objectForKey:@"msg"] toView:self.view];
                [headerView endRefreshing];
                [footerView endRefreshingWithoutIdle];
            }
        }];

        [request setFailedBlock:^{
            [XDTools hideProgress:self.view];
            [headerView endRefreshing];
            [footerView endRefreshingWithoutIdle];
            NSError *error = [mrequest error];
            DDLOG_CURRENT_METHOD;
            DDLOG(@"error=%@",error);
            if (mrequest.error.code == 2) {
                [XDTools showTips:@"网络请求超时" toView:self.view];
            }
        }];
        if (!notFirst) {
            [XDTools showProgress:self.view];
            notFirst = YES;
        }
        [request startAsynchronous];

    }
    else
    {
        [XDTools showTips:brokenNetwork toView:self.view];
        [headerView endRefreshing];
        [footerView endRefreshingWithoutIdle];
    }
}

#pragma mark - TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 115;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * cellIde = @"cell";
    TypeListTableViewCell * cell = [myTableView dequeueReusableCellWithIdentifier:cellIde];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"TypeListTableViewCell" owner:self options:nil]lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.lineIV.frame = CGRectMake(0, 113.5, 320, .5f);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.headIV.contentMode = UIViewContentModeScaleToFill;
        
    }
    cell.contentLB.frame = CGRectMake(100, 53, 186, 41);
    [cell.headIV setImageWithURL:[NSURL URLWithString:dataArray[indexPath.row][@"goods_img"]] placeholderImage:nil];
//    cell.headIV.layer.borderColor = [UIColor redColor].CGColor;
//    cell.headIV.layer.borderWidth = 1;
    cell.nameLB.text = dataArray[indexPath.row][@"goods_name"];
    cell.contentLB.text = dataArray[indexPath.row][@"goods_desc"];
    [cell.contentLB sizeToFit];
    if (cell.contentLB.frame.size.height > 41) {
        cell.contentLB.frame = CGRectMake(100, 53, 186, 41);
    }
//    cell.contentLB.backgroundColor = [UIColor orangeColor];
    return cell;
}

#pragma mark - TableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsDetailViewController * detail = [[GoodsDetailViewController alloc] init];
    detail.goodsID = dataArray[indexPath.row][@"goods_id"];
    [self.navigationController pushViewController:detail animated:YES];
}



#pragma mark - MJRefreshView Delegate
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView{
    if (refreshView == headerView) {
        [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(getNewData) userInfo:nil repeats:NO];
    }else if (refreshView == footerView) {
        [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(getNextData) userInfo:nil repeats:NO];
    }
}

- (void)getNewData{
    currentPage = 1;
    totalCount = 0;

    [self getDataWithSign:@"0"];

}


- (void)getNextData{
    if (totalCount == -999)
    {
        [headerView endRefreshing];
        [footerView endRefreshingWithoutIdle];
        [XDTools showTips:@"没有更多数据" toView:self.view];
        [self yoffset:dataArray andTableview:myTableView];
    }
    else
    {
        currentPage++;
        [self getDataWithSign:@"1"];

    }
}

- (void)yoffset:(NSMutableArray *)arr andTableview:(UITableView *)tableview
{
    CGFloat y = tableview.contentOffset.y;
    tableview.contentOffset = CGPointMake(0, y-60);
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
